// state = [{id: 1, title: '做核酸', done: false}, {id: 2, title: '理发', done: true}]
//比较重要的一步
/**
 * action  最关键的一步
 *  {type: 'add_todo' payload: {id: 3, title: 'xx', done: false} }
 *  {type: 'remove_todo' payload: 2 }
 *  {type: 'check_todo', payload: {id: 3, done: false}}
 *  {type: 'check_all_todo', payload: false}
 *  {type: 'remove_done_todo', payload: undefined}
 *  {type: 'init_todo', payload: [{id:1, title: 'xx', done: false}, {id:2, title: 'xxx', done: true}]}
 */
// import axios from 'axios';
import request from '../../utils/request'

let todoReducer = (state=[], action) => {
  switch (action.type) {
    case 'init_todo': // dispatch({type:'init_todo', payload: []})
      return [...action.payload];
    case 'add_todo':
      return [...state, action.payload]
    case 'remove_todo':
      return state.filter(item => item.id !== action.payload);
    case 'check_todo':
      return state.map(item => {
        if(item.id === action.payload.id){
          item.done = action.payload.done;
        }
        return item;
      })
    case 'check_all_todo':
      return state.map(item => {
        item.done = action.payload
        return item;
      });
    case 'remove_done_todo':
      return state.filter(item => !item.done);
    default:
      return state;
  }
}

export default todoReducer;

//声明 action creator
//新增任务 action creator
export function addTodoAction(payload){
  return {
    type: 'add_todo',
    payload: payload
  }
}

//删除任务 action creator
export function removeTodoAction(id){
  return {
    type: 'remove_todo',
    payload: id
  }
}

//更新单个任务 action creator
export function checkTodoAction(payload){
  return {
    type: "check_todo",
    payload: payload
  }
}

//批量更新任务 action creator
export function checkAllTodoAction(done){
  return {
    type: 'check_all_todo',
    payload: done
  }
}

//移除已经完成的任务
export function removeDoneTodo(){
  return {
    type: 'remove_done_todo'
  }
}

//初始化
export function initTodo(payload){
  return {
    type: 'init_todo',
    payload: payload
  }
}

/**************异步更新状态************* */
//获取 todo 的数据,并更新 redux 状态
export function requestGetTodo(){
  return async dispatch => {
    let result = await request.get('/todos')
    dispatch(initTodo(result));
  }
}

//新增任务数据
export function requestAddTodo(title){
  return async dispatch => {
    let result = await request.post('/todos', {title: title, done: false})
    //同步的更新 redux 的状态
    dispatch(addTodoAction(result));
  }
}

//更新任务的完成状态 store.dispatch(requestUpdateTodo(2, true));
export function requestUpdateTodo(id, done){
  return async dispatch => {
    let result = await request.patch(`/todos/${id}`, {done: done})
    dispatch(checkTodoAction({id: id, done: result.done}))
  }
}

//删除某个任务
export function requestRemoveTodo(id){
  return dispatch => {
    request.delete(`/todos/${id}`)
    .then(v => {
      //更新 redux 中的状态值
      dispatch(removeTodoAction(id));
    })
  }
}

